// 用户模型
const { DataTypes } = require("sequelize");
const sequelize = require("../config/sequelize.js");
const MembershipLevel = require("./MembershipLevel.js");
const Animal = require("./Animal.js");

const User = sequelize.define("user", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
    allowNull: false
  },
  username: {
    type: DataTypes.STRING(50),
    allowNull: false
  },
  email: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true
  },
  password: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  membershipLevelId: {
    type: DataTypes.STRING(20),
    allowNull: true,
    field: 'membership_level_id',
    references: {
      model: 'membership_levels',
      key: 'id'
    }
  },
  isMember: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    field: 'is_member'
  },
  isAdmin: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
    field: 'is_admin'
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: true
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: true
  }
}, {
  tableName: "users",
  timestamps: true,
  indexes: [
    { fields: ['email'] }
  ]
});

// 设置关联关系
User.belongsTo(MembershipLevel, { foreignKey: 'membershipLevelId' });

// 用户和动物的多对多关系（点赞）
User.belongsToMany(Animal, {
  through: 'user_likes',
  foreignKey: 'user_id',
  otherKey: 'animal_id',
  as: 'likedAnimals'
});

module.exports = User;